from scipy.misc import imread, imresize, imsave
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.pyplot import imshow
import pandas as pd
from imageio import imwrite
from collections import Counter

def ind_cnt(yi, xi):
    xi[xi < 0] = 0
    xi[xi >= 330] = 329
    yi[yi < 0] = 0
    yi[yi >= 110] = 109
    M = Counter(zip(yi, xi))
    return M


train = pd.read_hdf('../input/train.h5')

# for type in ['围网', '刺网', '拖网']:
#     ships = train.loc[train['type'] == type, 'ship'].unique()
#     for i in range(len(ships)):
#         I = np.zeros((110, 330))
#         ship = ships[i]
#         data0 = train.loc[train['ship'] == ship, :]
#         lon, lat = data0['y'] / 50000, data0['x'] / 200000
#         xi = ((lon - 90) / 0.1).astype(np.int)
#         yi = ((lat - 25) / 0.1).astype(np.int)
#         W = ind_cnt(yi, xi)
#         print(type, ': 停驻位置个数', len(W), ',', 'max:', max(W.values()))
#         xi1, yi1 = np.array(list(W.keys()))[:, 0], np.array(list(W.keys()))[:, 1]
#         I[xi1, yi1] = list(W.values())
#         I1 = I/np.max(I)*255
#         I2 = I1.astype(np.uint8)
#         # imshow(I2)
#         # plt.show()
#         imwrite(f'../img1/{type}/{ship}.png', I2)
#         # break



arr = []
ships = train.loc[:, 'ship'].unique()
for i in range(len(ships)):
    I = np.zeros((110, 330))
    ship = ships[i]
    data0 = train.loc[(train['ship'] == ship) & (train['ship'] == ship), :]
    lon, lat = data0['y'] / 50000, data0['x'] / 200000
    xi = ((lon - 90) / 0.1).astype(np.int)
    yi = ((lat - 25) / 0.1).astype(np.int)
    W = ind_cnt(yi, xi)
    print(i, ': 停驻位置个数', len(W), ',', 'max:', max(W.values()))
    xi1, yi1 = np.array(list(W.keys()))[:, 0], np.array(list(W.keys()))[:, 1]
    I[xi1, yi1] = list(W.values())
    I1 = I/np.max(I)*255
    I2 = I1.astype(np.uint8)
    arr += [I2.reshape(-1)]

Arr = np.array(arr)


res = pd.DataFrame(Arr)
type_map = dict(zip(train['type'].unique(), np.arange(3)))
res['label'] = train.drop_duplicates(['ship', 'type'])['type'].reset_index()['type'].map(type_map)
res['ship'] = train.drop_duplicates(['ship', 'type']).reset_index()['ship']
res.to_hdf('../data/im1x3.h5', 'df', mode='w')
res = res.set_index('ship')


# /Users/lz/anaconda3/lib/python3.7/site-packages/pandas/io/pytables.py:274: PerformanceWarning:
# your performance may suffer as PyTables will pickle object types that it cannot
# map directly to c-types [inferred_type->mixed-integer,key->axis0] [items->None]
#   f(store)